package com.gzx.plugin.data.wckj.api;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gzx.plugin.data.core.utils.MD5Utils;
import com.gzx.plugin.data.wckj.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ApiFactory {

    public static ApiResponse callRemoteApi(String partnerUserId, String url, String servicePath, String orgCode, String orgPwd) {
        try {
            log.info("开始启动查询5.2在催合同信息接口......");
            long apiBeginTime = System.currentTimeMillis();//记录接口开始时间
            HttpRequest post = apiRequestBuilder(partnerUserId, url, servicePath, orgCode, orgPwd);
            HttpResponse execute = post.execute();
            int statusCode = execute.getStatus();
            if (statusCode == 200) {
                String body = execute.body();
                log.info("查询在催合同信息接口响应参数:{}", body);
                log.info("本次查询远端{}接口耗时:{}", orgCode, System.currentTimeMillis() - apiBeginTime);
                return apiResponseBuiler(body, partnerUserId);
            } else {
                log.error("接口返回码为{}，调用失败，我方请求报文为：{}", statusCode, post);
                return null;
            }
        } catch (Exception e) {
            log.error("调用5.2查询在催合同信息接口失败...", e);
            return null;
        }
    }

    public static HttpRequest apiRequestBuilder(String partnerUserId, String url, String servicePath, String orgCode, String orgPwd) {
        Map<String, Object> paramMap = new HashMap<>();
        // 请求体参数对象 params
        paramMap.put("orgCode", orgCode);
        paramMap.put("orgPwd", orgPwd);
        paramMap.put("partnerUserId", partnerUserId);

        String secret = MD5Utils.toMD5(orgCode + orgPwd);
        // 创建HTTP请求对象
        HttpRequest post = HttpUtil.createPost(url + servicePath);
        // 设定请求头
        post.header(Header.CONTENT_TYPE, "application/json");
        post.header("Secret", secret);
        // 设定请求体
        post.body(JSON.toJSONString(paramMap));
        //设置超时时间为10秒
        post.timeout(10000);
        return post;
    }

    public static ApiResponse apiResponseBuiler(String requestBody, String partnerUserId) {
        // 解析结果
        JSONObject jsonObject = JSON.parseObject(requestBody);
        String status = jsonObject.getString("status");
        if ("0".equals(status)) {
            String data = jsonObject.getString("data");
            if (StringUtils.isNotBlank(data)) {
                ApiResponse apiResponse = JSON.parseObject(data, ApiResponse.class);
                //用户信息对象
                List<JudgeUserInfo> userInfo = apiResponse.getUserInfo();
                if (userInfo != null && userInfo.size() > 0) {
                    userInfo.stream().forEach(item -> {
                        item.setYwyhId(partnerUserId);
                        String mobileListStr = item.getMobileList(); // 例如: "[\"18888888888\",\"15555555555\",\"13333333333\"]"
                        JSONArray jsonArray = new JSONArray(mobileListStr); // 解析为 JSONArray
                        String mobileListCommaSeparated = jsonArray.join(",").replaceAll("\"", ""); // 转换为逗号分隔字符串并去掉引号
                        item.setMobileList(mobileListCommaSeparated); // 设置新的 mobileList
                    });
                }
                //借款信息列表
                List<JudgeTransferInfo> transfer = apiResponse.getTransfer();
                if (transfer != null && transfer.size() > 0) {
                    transfer.stream().forEach(item -> item.setYwyhId(partnerUserId));
                }

                //还款计划列表
                List<JudgeRepayPlanInfo> replayPlan = apiResponse.getReplayPlan();
                if (replayPlan != null && replayPlan.size() > 0) {
                    replayPlan.stream().forEach(item -> item.setYwyhId(partnerUserId));
                }

                //还款信息列表
                List<JudgeRepayInfo> repay = apiResponse.getRepay();
                if (repay != null && repay.size() > 0) {
                    repay.stream().forEach(item -> item.setYwyhId(partnerUserId));
                }

                //代偿信息列表
                List<JudgeLoanInfo> loan = apiResponse.getLoan();
                if (loan != null && loan.size() > 0) {
                    loan.stream().forEach(item -> item.setYwyhId(partnerUserId));
                }
                return apiResponse;
            } else {
                log.info("未查询到该用户在催合同信息，用户id为：{}", partnerUserId);
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                }
                return null;
            }
        } else {
            if ("C_9000011".equals(status)) {
                log.info("超过当日请求次数限制, 异常用户id:{}", partnerUserId);
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                }
            }
            return null;
        }
    }
}
